var dateFormat = function() {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function(val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function(date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d: d,
                dd: pad(d),
                ddd: dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m: m + 1,
                mm: pad(m + 1),
                mmm: dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy: String(y).slice(2),
                yyyy: y,
                h: H % 12 || 12,
                hh: pad(H % 12 || 12),
                H: H,
                HH: pad(H),
                M: M,
                MM: pad(M),
                s: s,
                ss: pad(s),
                l: pad(L, 3),
                L: pad(L > 99 ? Math.round(L / 10) : L),
                t: H < 12 ? "a" : "p",
                tt: H < 12 ? "am" : "pm",
                T: H < 12 ? "A" : "P",
                TT: H < 12 ? "AM" : "PM",
                Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd HH:MM:ss",
    isoDateTimeShort: "yyyy-mm-dd HH:MM",
    isoUtcDateTime: "UTC:yyyy-mm-dd HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
}; // For convenience...
Date.prototype.format = function(mask, utc) {
    return dateFormat(this, mask, utc);
};

/**
 * 工具类:提供全局公用方法；
 * @author: tianyu;
 */
var TimeUtil =  (function () {	
    var currentPageId = "";
   
    var staticMethods = {
    	 /**
    	  * 获取当前日期对象;
    	  */	
         curDateTime:function() {
        	return new Date();
         },
        
        /**获取当前日期字符串,格式:2016年05月25日;*/
        getNowDate:function(){
        	var nowDate = this.curDateTime();
        	return  nowDate.getFullYear() + "年" + nowDate.getMonth() +"月" + nowDate.getDate() + "日";
        },
        
        isLeapYear : function(){  
	         var flag = false;  
	         var date =this.curDateTime();
	         var year = date.getFullYear();
	         if((year% 4 == 0 && year % 100 !=0)  
	                 || (this.getYear() % 400 == 0)){  
	             flag = true;  
	         }         
	         return flag;  
	     },
	     /**获取当前月份最大天数;*/
	     getMaxDaysByMonth:function(month){ 
	         var days = 31;  
	         switch(month){  
	             case 2:  
	                 if(this.isLeapYear()){  
	                     days = 29;  
	                 }else{  
	                     days = 28;  
	                 }  
	                 break;  
	             case 4:  
	             case 6:  
	             case 9:  
	             case 11:  
	                 days = 30;  
	                 break;  
	             default:  
	                 break;  
	         }  
	         return days;  
	     },
	     /**获取当前日期字符串:yyyy-mm-dd;*/
	     getNowDateStr:function(){
	        	var nowDate = this.curDateTime();
	        	var month = (Number(nowDate.getMonth())+1);
	        	var day = nowDate.getDate();
	        	if(month < 10){
	        		month = "0"+month;
	        	}
	        	if(day < 10){
	        		day = "0"+day;
	        	}
	        	
	            return  nowDate.getFullYear() + "-" + month +"-" + day;
	    },
	    /**字符串日期转换为Date;*/
	    str2Date :function (dateStr){
	        var dr = dateStr.split("-");
	        return new Date((dr[0]),(parseInt(dr[1])-1),(dr[2]))
	    },
	    /**获取当前日期延后X天的日期:yyyy-mm-dd;*/
	    getAfterDateStr:function(dateStr,days){
	    	
	    	return new Date((this.str2Date(dateStr).valueOf())+(Number(days)*24*60*60*1000)).format("yyyy-mm-dd");
	    },
        getAfterDate:function(dateStr,days){
	    	
	    	return new Date((this.str2Date(dateStr).valueOf())+(Number(days)*24*60*60*1000));
	    },
        getBeforeDateStr:function(dateStr,days){
	    	
	    	return new Date((this.str2Date(dateStr).valueOf())-(Number(days)*24*60*60*1000)).format("yyyy-mm-dd");
	    },
        getBeforeDate:function(dateStr,days){
	    	
	    	return new Date((this.str2Date(dateStr).valueOf())-(Number(days)*24*60*60*1000));
	    },
	    /**获取下个月份;*/
	    getNextMonth:function(){
	    	var nowDate =this.curDateTime();
	    	return (Number(nowDate.getMonth())+2);
	    },
	    
	    /**获取当前月份次月份的最大年月日:yyyy-mm-dd;*/
	    getNextMonthMaxDate:function(){
	    	var nowDate =this.curDateTime();
	    	var nextMonth = (Number(nowDate.getMonth())+2);
	    	var maxDays = this.getMaxDaysByMonth(nextMonth);
	    	return nowDate.getFullYear() + "-" + nextMonth +"-" + maxDays;
	      	
	    },
	    getNextMonthMaxDateByMonth:function(month){
	    	var nowDate =this.curDateTime();
	    	var nextMonth = (Number(month)+2);
	    	var maxDays = this.getMaxDaysByMonth(nextMonth);
	    	return nowDate.getFullYear() + "-" + nextMonth +"-" + maxDays;
	      	
	    },
	    
	    /**比较日期大小;date1>date2 return false;*/
	    compareDate:function(date1,date2){
	    	var dateMS_1= this.str2Date(date1).valueOf();
	    	var dateMS_2= this.str2Date(date2).valueOf();
	    	if(dateMS_1<=dateMS_2){
	    		return true;
	    	}
	    	return false;
	    },
	    
	    dateDiffValue:function (date1,date2){
	    	var dateMS_1= this.str2Date(date1).valueOf();
	    	var dateMS_2= this.str2Date(date2).valueOf();
	    	if(dateMS_1<dateMS_2){
	    		return -1;
	    	}
	    	return Number(dateMS_1) - Number(dateMS_2);
	    },
	    
	    initBeginTimeWidget:function(pageId,params){
	    	 if(params&&!params.selectEvent){
	    		 params.selectEvent = function(){};
	    	 }
	    	 $("#"+pageId+" #date-start1").mobiscroll().date({
	             theme: 'ios',
	             model: 'scroller',
	             lang: 'zh',
	             display: 'bottom',
	             dateFormat: 'yy-mm-dd',
	             defaultValue: params.defaultValue,
	             maxDate: params.maxDate,
	             minDate: params.minDate,
	             onSelect:params.selectEvent
	         });
	    
	    },
	    initEndTimeWidget:function(pageId,params){
	    	 if(params&&!params.selectEvent){
	    		 params.selectEvent = function(){};
	    	 }
	    	 $("#"+pageId+" #date-end1").mobiscroll().date({
	             theme: 'ios',
	             model: 'scroller',
	             lang: 'zh',
	             display: 'bottom',
	             dateFormat: 'yy-mm-dd',
	             defaultValue: params.defaultValue,
	             maxDate: params.maxDate,
	             minDate: params.minDate,
	             onSelect:params.selectEvent
	         });
	    
	    },
	    getActivityEndTimeByType:function(beginDateStr,actType){
	    	      var endDateTime = "";
	    	      if(actType == ACTIVITY_TYPE.PASSWORD_PREFERENTIAL.val){//口令优惠会员;
	    		    endDateTime = this.getAfterDateStr(beginDateStr,32);
	    	      }else{ //默认延后30天;
	    	    	endDateTime = this.getAfterDateStr(beginDateStr,30);
	    	      } 
	    	      //else if(actType == ACTIVITY_TYPE.NEXT_MONTH_BIRTHDAY.val){//次月生日会员;
	              //    var curMonth = beginDateStr.split("-")[1];
	    	   	  //	    endDateTime = this.getNextMonthMaxDateByMonth(curMonth);
	    	     // }
	           
	    	return endDateTime;
	    	
	    },	    
	    /**获取日期之间间隔天数;*/
	    diffDateDays:function(start,end){
	    	if(start==null||start.length==0||end==null||end.length==0){
	    	   return -1;
	    	}
	    	var arr=start.split("-");
	    	var starttime=new Date(arr[0],parseInt(arr[1]-1),arr[2]);
	    	var starttimes=starttime.getTime();
	    	var arrs=end.split("-");
	    	var endtime=new Date(arrs[0],parseInt(arrs[1]-1),arrs[2]);
	    	var endtimes=endtime.getTime();
	    	var intervalTime = endtimes-starttimes;//两个日期相差的毫秒数 一天86400000毫秒
	    	if(intervalTime<0){
	    		return -1;
	    	}
	    	var Inter_Days = ((intervalTime).toFixed(2)/86400000)+1;//加1，是让同一天的两个日期返回一天
	    	return Inter_Days;
	    }, 
	    getActivityTicketEndTime:function(ticketStartDateStr,actEndDateStr){
	    	var diffMSDays = this.diffDateDays(ticketStartDateStr,actEndDateStr);
	    	if(diffMSDays==-1){
	    		return this.getAfterDateStr(ticketStartDateStr,30);
	    	}
	    	if(diffMSDays >= 30){
	    		return actEndDateStr;
	    	}
	        return this.getAfterDateStr(ticketStartDateStr,30);
	    	
	    }
	    
        
    };
    
  return  staticMethods;
	   
})();